package com.zsl.swing.redis.desktop.window.ext;

import com.zsl.swing.redis.desktop.utils.StringUtils;

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import java.util.Objects;

public class JIntegerField extends JTextField {

    public JIntegerField(){
        this(null,null,0);
    }

    public JIntegerField(int columns){
        this(null,null,columns);
    }

    public JIntegerField(String text, int columns){
        this(null, text, columns);
    }

    public JIntegerField(Document doc, String text, int columns){
        super(doc, text, columns);
        this.setDocument(new NumberDocument());
    }


    public Integer getInteger(){
        String text = this.getText();
        return StringUtils.isEmpty(text) ? 0: Integer.parseInt(text);
    }

    public void setInteger(Integer value){
        this.setText(String.valueOf(value));
    }


    private static class NumberDocument extends PlainDocument{

        public NumberDocument(){
            super();
        }


        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if(Objects.isNull(str)){
                return;
            }else{
                char[] chars = str.toCharArray();

                StringBuilder sb = new StringBuilder();
                for(char c: chars){
                    if(c >= '0' && c <= '9'){
                        sb.append(c);
                    }
                }

                super.insertString(offs, sb.toString(), a);
            }
        }
    }
}
